package com.nercel.dsj.gksales.shiro;

import org.apache.shiro.web.filter.mgt.FilterChainManager;
import org.apache.shiro.web.filter.mgt.PathMatchingFilterChainResolver;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.util.Iterator;

/**
 * @Author tomsun28
 * @Description
 * @Date 21:12 2018/4/20
 */
public class RestPathMatchingFilterChainResolver extends PathMatchingFilterChainResolver {

    private static final Logger LOGGER = LoggerFactory.getLogger(RestPathMatchingFilterChainResolver.class);

    public RestPathMatchingFilterChainResolver() {
        super();
    }

    public RestPathMatchingFilterChainResolver(FilterConfig filterConfig) {
        super(filterConfig);
    }

    @Override
    public FilterChain getChain(ServletRequest request, ServletResponse response, FilterChain originalChain) {
        FilterChainManager filterChainManager = this.getFilterChainManager();
        if (!filterChainManager.hasChains()) {
            return null;
        } else {
            String requestURI = this.getPathWithinApplication(request);
            Iterator var6 = filterChainManager.getChainNames().iterator();
            String pathPattern;
            boolean flag;
            String[] strings;
            do {
                if (!var6.hasNext()) {
                    return null;
                }
                pathPattern = (String) var6.next();
                strings = pathPattern.split(":");
                if (strings.length == 2) {
                    flag = !WebUtils.toHttp(request).getMethod().toUpperCase().equals(strings[0].toUpperCase());
                    pathPattern = strings[1];
                } else {
                    flag = false;
                    pathPattern = strings[0];
                }
            } while (!this.pathMatches(pathPattern, requestURI) || flag);

            if (LOGGER.isTraceEnabled()) {
                LOGGER.trace("Matched path pattern [" + pathPattern + "] for requestURI [" + requestURI
                        + "].  Utilizing corresponding filter chain...");
            }
            if (strings.length == 2) {
                pathPattern = WebUtils.toHttp(request).getMethod().toUpperCase().concat(":").concat(pathPattern);
            }
            return filterChainManager.proxy(originalChain, pathPattern);
        }
    }

}
